package dynamicprogramming.最长公共子序列;

public class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        /**
         * f[i][j] 表示 text1 从 0-i 和 0 text2 0 - j 中最大子序列长度
         * 则有 f[i][j]
         * text1[i] == text2[j] f[i][j] = f[i-1][j-1] + 1
         * text1[i] != text2[j] f[i][j] = max(f[i-1][j] , f[i][j-1])
         * 初始化： f[0][0] f[1][0] f[0][1]
         */
        int len1 = text1.length();
        int len2 = text2.length();
        int[][] f = new int[len1 + 1][len2 + 1];
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (text1.charAt(i -1 ) == text2.charAt(j - 1 )) {
                    f[i][j] = f[i - 1][j - 1] + 1;
                } else {
                    f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
                }
            }
        }
        return f[len1][len2];
    }
}
